import { h, ref } from 'vue';
import { NSwitch } from 'naive-ui';
import { cloneDeep } from 'lodash-es';
import { renderFile } from '@/utils';
import { Switch } from '@/api/cardBanners';
import { useDictStore } from '@/store/modules/dict';
import { usePermission } from '@/hooks/web/usePermission';

const dict = useDictStore();
const { hasPermission } = usePermission();
const $message = window['$message'];

export class State {
  public id = 0; // id
  public categoryId = null; // category_id
  public imageUrl = ''; // image_url
  public title = ''; // title
  public subtitle = ''; // subtitle
  public link = ''; // link
  public sortOrder = 0; // sort_order
  public isActive = 2; // is_active
  public createdAt = ''; // created_at

  constructor(state?: Partial<State>) {
    if (state) {
      Object.assign(this, state);
    }
  }
}

export function newState(state: State | Record<string, any> | null): State {
  if (state !== null) {
    if (state instanceof State) {
      return cloneDeep(state);
    }
    return new State(state);
  }
  return new State();
}

// 表单验证规则
export const rules = {
  categoryId: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'number',
    message: '请输入category_id',
  },
  imageUrl: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入image_url',
  },
  title: {
    required: true,
    trigger: ['blur', 'input'],
    type: 'string',
    message: '请输入title',
  },
};

// 表格搜索表单

// 表格列
export const columns = [
  {
    title: 'id',
    key: 'id',
    align: 'left',
    width: -1,
  },
  {
    title: 'category_id',
    key: 'categoryId',
    align: 'left',
    width: -1,
  },
  {
    title: 'image_url',
    key: 'imageUrl',
    align: 'left',
    width: -1,
    render(row: State) {
      return renderFile(row.imageUrl);
    },
  },
  {
    title: 'title',
    key: 'title',
    align: 'left',
    width: -1,
  },
  {
    title: 'subtitle',
    key: 'subtitle',
    align: 'left',
    width: -1,
  },
  {
    title: 'link',
    key: 'link',
    align: 'left',
    width: -1,
  },
  {
    title: 'sort_order',
    key: 'sortOrder',
    align: 'left',
    width: -1,
  },
  {
    title: 'is_active',
    key: 'isActive',
    align: 'left',
    width: -1,
    render(row: State) {
      return h(NSwitch, {
        value: row.isActive === 1,
        checked: '开启',
        unchecked: '关闭',
        disabled: !hasPermission(['/cardBanners/switch']),
        onUpdateValue: function (e) {
          console.log('onUpdateValue e:' + JSON.stringify(e));
          row.isActive = e ? 1 : 2;
          Switch({ id: row.id, key: 'is_active', value: row.isActive }).then((_res) => {
            $message.success('操作成功');
          });
        },
      });
    },
  },
  {
    title: 'created_at',
    key: 'createdAt',
    align: 'left',
    width: -1,
  },
];

// 加载字典数据选项
export function loadOptions() {
  dict.loadOptions(['cardCategoriesOption']);
}